package org.lh.ibernate.core.impl;

import org.lh.ibernate.annotation.Column;
import org.lh.ibernate.annotation.Id;
import org.lh.ibernate.annotation.Table;
import org.lh.ibernate.core.IDelete;
import org.lh.ibernate.utils.IDbUtil;
import org.lh.ibernate.utils.impl.DbUtil;
import org.lh.ibernate.common.CommonUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DeleteUtil<T,PK>  implements IDelete<T,PK> {

    private IDbUtil iDbUtil=new DbUtil();

    @Override
    public void delete(Class<T> clazz, PK pk) throws Exception {
        StringBuffer sql=new StringBuffer("delete from ");
        boolean tableNameExist=clazz.isAnnotationPresent(Table.class);
        if(tableNameExist) {
            Object pkValue=new Object();
            String pkName=new String();
            Table annoTableName = (Table) clazz.getAnnotation(Table.class);
            String tableName = annoTableName.name(); //获取表名称
            sql.append(tableName);
            Field[] fields=clazz.getDeclaredFields();
            for (Field fieldItem : fields) {
                if(fieldItem.isAnnotationPresent(Id.class)){
                    Column column=fieldItem.getAnnotation(Column.class);
                    pkName=column.value();
                    break;
                }
            }
            sql.append(" where "+pkName+"=?");
            CommonUtil.printSql(new String(sql));
            List<Object> paramsList=new ArrayList<Object>();
            paramsList.add(pk);
            iDbUtil.executeUpdate(new String(sql),paramsList);
        }
    }
}
